package com.cxria.springboottest.utils;

import com.cxria.springboottest.dto.Status;
import com.cxria.springboottest.enums.StatusCodeEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ErrorUtils {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ObjectMapper objectMapper;

    public void throwException(Status status){
        String message = null;
        try {
            message = objectMapper.writeValueAsString(status);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
        }
        throw new RuntimeException(message);
    }

    public void throwException(Exception e){
        String message = null;
        try {
            Status status = new Status(Status.ERROR, StatusCodeEnum.UNKNOWN_ERROR, e.getMessage());
            message = objectMapper.writeValueAsString(status);
        } catch (JsonProcessingException e2) {
            logger.error(e2.getMessage());
        }
        throw new RuntimeException(message);
    }

}
